package com.lagou.config;

import com.alibaba.fastjson.JSONObject;
import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.HashSet;
import java.util.List;

public class XMLMapperBuilder {

  private final Configuration configuration;

  public XMLMapperBuilder(Configuration configuration) {
    this.configuration = configuration;
  }

  public void parse(InputStream inputStream) throws DocumentException {

    Document document = new SAXReader().read(inputStream);
    Element rootElement = document.getRootElement();
//    List<Element> elements = rootElement.elements();
//    HashSet<Object> objects = new HashSet<>();
//    elements.stream().forEach(x->{
//      objects.add(x.getName()) ;
//    });
//    System.out.println(JSONObject.toJSONString(objects));
    String namespace = rootElement.attributeValue("namespace");

    List<Element> list = rootElement.selectNodes("//select");
    setConfigStatemanetMapper(list, namespace, "select");

    List insertList = rootElement.selectNodes("//insert");
    setConfigStatemanetMapper(insertList, namespace, "insert");
    List updateList = rootElement.selectNodes("//update");
    setConfigStatemanetMapper(updateList, namespace, "update");
    List deleteList = rootElement.selectNodes("//delete");
    setConfigStatemanetMapper(deleteList, namespace, "delete");
  }

  private void setConfigStatemanetMapper(List<Element> list, String namespace, String signature) {

    list.stream()
        .forEach(
            x -> {
              MappedStatement build =
                  MappedStatement.builder()
                      .id(x.attributeValue("id"))
                      .paramterType(x.attributeValue("paramterType"))
                      .resultType(x.attributeValue("resultType"))
                      .sql(x.getTextTrim())
                      .signature(signature)
                      .build();
              String key = namespace + "." + x.attributeValue("id");
              configuration.getMappedStatementMap().put(key, build);
            });
  }
}
